package com.lk.template.config;

import com.lk.template.constants.RedisPrefixConstants;
import com.lk.template.context.UserContext;
import com.lk.template.exception.CommonException;
import com.lk.template.exception.EmError;
import com.lk.template.utils.JwtTokenUtil;
import com.lk.template.utils.RedisUtil;
import com.lk.template.vo.UserVo;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

/**
 * @author lk
 * @date 2024/5/24 10:41
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

  private final PathMatcher pathMatcher = new AntPathMatcher();

  @Resource
  private RedisUtil redisUtil;

  /**
   * 预处理回调方法，实现处理器的预处理
   */
  @Override
  public boolean preHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler) throws Exception {
//    //鉴权放行
//    String requestURI = request.getRequestURI();
//    for (String path : ExcludePaths.excludePath) {
//      if (pathMatcher.match(path, requestURI)) {
//        return true;
//      }
//    }
//    // 解析token
//    String token = request.getHeader("token");
//    if (Objects.isNull(token)) {
//      throw new CommonException(EmError.AUTH_TOKEN_EXPIRED);
//    }
//    String UserId = JwtTokenUtil.validateToken(token);
//    if (Objects.isNull(UserId)) {
//      throw new CommonException(EmError.AUTH_TOKEN_EXPIRED);
//    }
//    // 获取用户信息
//    UserVo userVo = (UserVo) redisUtil.getObject(RedisPrefixConstants.XXX_USER_INFO + UserId);
//    if (Objects.isNull(userVo)) {
//      throw new CommonException(EmError.AUTH_TOKEN_EXPIRED);
//    }
//    // 用户是否被禁用
//    if (userVo.getWhetherBlock()) {
//      throw new CommonException(EmError.AUTH_USER_IS_BLOCK_LOGIN);
//    }
//    // 存入缓存
//    UserContext.setUser(userVo);
    return true;
  }

  /**
   * 业务层处理
   */
  @Override
  public void postHandle(HttpServletRequest request,
                         HttpServletResponse response,
                         Object handler,
                         @Nullable ModelAndView modelAndView) throws Exception {

  }

  /**
   * 整个请求处理完毕回调方法
   */
  @Override
  public void afterCompletion(HttpServletRequest request,
                              HttpServletResponse response,
                              Object handler,
                              @Nullable Exception ex) throws Exception {

  }

}
